<template>
  <view class="uv-page" style="background-color: #fff;">
    <view class="uv-demo-block">
      <view class="uv-demo-block__content">
        <uv-form :model="form" :rules="rules" ref="form1" labelWidth="auto">

          <uv-form-item prop="taskName" required label="任务名:" borderBottom>
            <uv-input v-model="form.taskName" placeholder="请输入任务名" border="none" clearable></uv-input>
          </uv-form-item>
          <uv-form-item prop="inspectorName" required label="检查人:" borderBottom @click="showInspectorSelect">
            <uv-input v-model="form.inspectorName" disabled disabledColor="#ffffff" placeholder="请选择检查人"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item prop="inspectDeadline" required label="检查截止:" borderBottom @click="inspectDeadlineOpen">
            <uv-input v-model="form.inspectDeadline" disabled disabledColor="#ffffff" placeholder="请选择检查截止日期"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-radio-group @change="changeInspectDeadline">
            <uv-radio
                shape="square"
                :customStyle="{margin: '8px'}"
                v-for="(item, index) in commonTime"
                :key="index"
                :label="item"
                :name="item">
            </uv-radio>
          </uv-radio-group>

          <uv-form-item prop="areaName" label="区域:" borderBottom @click="showAreaSelect">
            <uv-input v-model="form.areaName" disabled disabledColor="#ffffff" placeholder="请选择区域"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="timeType" label="类型:" borderBottom @click="showTypeTimeSelect">
            <uv-input v-model="timeTypeLabel" disabled disabledColor="#ffffff" placeholder="请选择类型"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item prop="remark" label="备注:" borderBottom>
            <uv-textarea v-model="form.remark" placeholder="请输入备注" clearable></uv-textarea>
          </uv-form-item>
          <uv-form-item prop="userName" label="执行人:" borderBottom @click="showUserSelect">
            <uv-input v-model="form.userName" disabled disabledColor="#ffffff" placeholder="请选择执行人"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>

          <uv-form-item prop="deadline" required label="执行截止:" borderBottom @click="deadlineOpen">
            <uv-input v-model="form.deadline" disabled disabledColor="#ffffff" placeholder="请选择执行截止日期"
                      border="none"></uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-radio-group @change="changeTimeType">
            <uv-radio
                shape="square"
                :customStyle="{margin: '8px'}"
                v-for="(item, index) in commonTime"
                :key="index"
                :label="item"
                :name="item">
            </uv-radio>
          </uv-radio-group>
          <uv-divider text=" 任务说明 " :dashed="true"></uv-divider>
          <uv-text align="center" prefixIcon="error-circle-fill" iconStyle="color:red;" size="16"
                   color="primary" text="注意规则"></uv-text>
          <view class="uv-content">
            <uv-parse :content="form.announcements"></uv-parse>
            <uv-album v-if="sampleGraph.length>0" :urls="sampleGraph" maxCount="3" multipleSize="160rpx"
                      singleSize="160rpx" space="8rpx"></uv-album>
          </view>
        </uv-form>

        <uv-button type="primary" text="下发" customStyle="margin-top: 10px" @click="submit"></uv-button>

        <!-- 选择执行人 -->
        <uv-picker ref="userSelectPicker"
                   :columns="userData"
                   @confirm="userSelect"
                   @cancel="userCancel"
                   keyName="realName"></uv-picker>

        <!-- 选择检查人 -->
        <uv-picker ref="inspectorSelectPicker"
                   :columns="userData"
                   @confirm="inspectorSelect"
                   @cancel="inspectorCancel"
                   keyName="realName"></uv-picker>

        <!-- 选择执行截止 -->
        <uv-datetime-picker :minDate="minDate" ref="deadlinePicker" v-model="deadlineDate"
                            mode="datetime"
                            :formatter="formatter"
                            @confirm="deadlineConfirm"
                            @cancel="deadlineCancel"></uv-datetime-picker>

        <!-- 选择任务类型 -->
        <uv-picker ref="typeTimeSelectPicker"
                   :columns="typeData"
                   @confirm="typeTimerSelect"
                   @cancel="typeTimeCancel"
                   keyName="dictValue"></uv-picker>

        <!-- 选择区域 -->
        <uv-picker ref="areaSelect"
                   :columns="areas"
                   @confirm="areaSelect"
                   keyName="title"
                   @cancel="areaCancel"></uv-picker>


        <!-- 选择检查截止日期 -->
        <uv-datetime-picker :minDate="minDate" ref="inspectDeadlinePicker" v-model="inspectDeadlineDate"
                            mode="datetime"
                            :formatter="formatter"
                            @confirm="inspectDeadlineConfirm"
                            @cancel="inspectDeadlineCancel"></uv-datetime-picker>
      </view>
    </view>
  </view>
</template>

<script>
import {
  formatTime,
  formatHmTime,
  rexTime,
  showToast, parseTime
} from '@/utils/media';

import TaskAPI from '@/api/task'
import CommonAPI from '@/api/common'
import DictAPI from "@/api/dict";
import AreaAPI from "@/api/area";

export default {
  data() {
    return {
      commonTime: ['11:00', '14:00', '17:30', '21:00', '23:59'],
      lastTime: '',
      sampleGraph: [],
      userData: [], // 待选用户列表
      typeData: [],
      timeTypeData: [],
      areas: [], // 区域列表
      timeTypeLabel: '',
      deadlineDate: new Date().getTime(),
      inspectDeadlineDate: new Date().getTime(),
      id: '',
      minDate: new Date().getTime(),
      form: {
        taskId: '',
        taskName: '', //任务标题
        areaId: '',
        areaName: '',
        userId: '',
        userName: '',
        inspectorId: '',
        inspectorName: '', // 检查人
        deadline: '', // 执行截止
        timeType: '', //
        announcements: '',
        sampleGraph: '', // 任务图示例
        remark: '',
        inspectDeadline: '', // 检查截止时间
      },
      rules: {
        taskName: {
          required: true,
          message: '请输入任务名',
          trigger: ['blur']
        },
        userName: {
          required: false,
          message: '请输入执行人',
          trigger: ['blur']
        },
        deadline: {
          required: true,
          message: '请选择执行截止时间',
          trigger: ['blur']
        },
        inspectorName: {
          required: true,
          message: '请输入检查人',
          trigger: ['blur']
        }
      },
    };
  },
  onLoad(e) {
    this.id = e.id
    this.init()

    this.taskDetail()
  },
  onReady() {
    this.$refs.deadlinePicker.setFormatter(this.formatter)
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.form1.setRules(this.rules)
  },
  methods: {
    changeTimeType(e) {
      this.form.deadline = formatHmTime(e)
    },
    changeInspectDeadline(e){
      this.form.inspectDeadline = formatHmTime(e)
    },
    init() {
      CommonAPI.userAttendance().then(res => {
        if (res.code !== 200) {
          return
        }
        this.userData = [[...res.data]]
      })

      DictAPI.dictByCodeList({
        code: 'task_time_type'
      }).then(res => {
        this.typeData = [[...res.data]]
        this.timeTypeData = res.data
      })

      AreaAPI.tree(1).then(res => {
        if (res.code !== 200) {
          return
        }
        this.areas = [[...res.data]]
      })
    },

    // 区域选择
    showAreaSelect() {
      this.$refs.areaSelect.open();
    },
    areaSelect(e) {
      // 正确获取选中项
      const element = e.value[0] // 单列选择器取第一个元素
      this.form.areaId = element.id
      this.form.areaName = element.title
    },
    areaCancel(e) {
      this.form.areaId = ''
      this.form.areaName = ''
    },
    // 任务类型选择
    showTypeTimeSelect() {
      this.$refs.typeTimeSelectPicker.open();
    },
    typeTimerSelect(e) {
      this.timeTypeLabel = e.value[0].dictValue
      this.form.timeType = e.value[0].dictKey
    },
    typeTimeCancel() {
      this.form.timeType = ''
      this.timeTypeLabel = ''
    },

    // 执行人选择
    showUserSelect() {
      this.$refs.userSelectPicker.open();
    },
    userSelect(e) {
      // 正确获取选中项
      const selectedUser = e.value[0] // 单列选择器取第一个元素
      this.form.userId = selectedUser.id
      this.form.userName = selectedUser.realName
    },
    userCancel() {
      this.form.userId = ''
      this.form.userName = ''
    },

    // 检查人选择
    showInspectorSelect() {
      this.$refs.inspectorSelectPicker.open();
    },
    inspectorSelect(e) {
      // 正确获取选中项
      const selectedUser = e.value[0] // 单列选择器取第一个元素
      this.form.inspectorId = selectedUser.id
      this.form.inspectorName = selectedUser.realName
    },
    inspectorCancel(e) {
      this.form.inspectorId = ''
      this.form.inspectorName = ''
    },


    // 检查截止日期选择
    inspectDeadlineOpen() {
      this.inspectDeadlineDate = this.form.inspectDeadline
      this.$refs.inspectDeadlinePicker.open();
    },
    inspectDeadlineConfirm(e) {
      console.info(e)
      this.form.inspectDeadline = formatTime(e.value)
      this.inspectDeadlineDate = formatTime(e.value)
    },
    inspectDeadlineCancel() {
      this.inspectDeadlineDate = new Date().getTime()
      this.form.inspectDeadline = ''
    },


    // 执行截止日期选择
    deadlineOpen() {
      this.deadlineDate = this.form.deadline
      this.$refs.deadlinePicker.open();
    },
    deadlineConfirm(e) {
      console.info(e)
      this.form.deadline = formatTime(e.value)
      this.deadlineDate = formatTime(e.value)
    },
    deadlineCancel() {
      this.deadlineDate = new Date().getTime()
      this.form.deadline = ''
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },

    // 任务详情
    async taskDetail() {
      await TaskAPI.taskDetail({
        id: this.id
      }).then(res => {
        if (res.code !== 200) {
          showToast({
            title: res.msg
          })
          return
        }
        // 将任务详情赋值给form
        this.assignmentForm({...res.data})
        // 示例图
        this.sampleGraph = this.form.sampleGraph?.split(',')
      })
    },
    assignmentForm(data) {
      this.form.taskId = data.id
      this.form.taskName = data.taskName
      this.form.areaId = data.areaIds
      this.form.areaName = data.areaName
      this.form.announcements = data.announcements
      this.form.sampleGraph = data.sampleGraph
      this.form.deadline = data.deadline ? formatHmTime(data.deadline) : ''
      this.form.inspectDeadline = data.inspectDeadline ? formatHmTime(data.inspectDeadline) : ''
      this.form.timeType = data.timeType
      this.timeTypeLabel = this.timeTypeData?.find(item => item.dictKey === data.timeType)?.dictValue
    },
    // 提交
    submit() {
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form1.validate().then(res => {
        //  检查执行截止是否小于当前时间
        if (parseTime(this.form.deadline) < new Date().getTime()) {
          uni.showToast({
            icon: 'none',
            title: '执行截止小于当前时间'
          })
          return
        }

        TaskAPI.taskAssign(this.form).then(res => {
          if (res.code === 200) {
            uni.showToast({
              icon: 'success',
              title: '提交成功'
            })
          } else {
            uni.showToast({
              icon: 'none',
              title: res.msg
            })
            return
          }
          uni.navigateTo({
            url: '/subpackage/task/task'
          })
        })
      }).catch(errors => {
        uni.showToast({
          icon: 'error',
          title: '校验失败'
        })
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.uv-page {
  padding: 15px 15px 40px 15px;
}

.uv-demo-block {
  margin-bottom: 22px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__title {
  font-size: 14px;
  color: #8f9ca2;
  margin-bottom: 8px;
}

.uv-demo-block__content {
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}

.uv-content {
  padding: 24rpx;
}
</style>